package com.yndsoft.jc.ui.categorypage;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yndsoft.jc.R;
import com.yndsoft.jc.activity.BaseActivity;
import com.yndsoft.jc.model.KeyValue_String;
import com.yndsoft.jc.model.Product;
import com.yndsoft.jc.model.ProductType;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.netutils.AppUtils;
import com.yndsoft.jc.netutils.DensityUtil;
import com.yndsoft.jc.ui.categorypage.adapter.ProductListAdapter;
import com.yndsoft.jc.ui.categorypage.entity.ProductListBean;
import com.yndsoft.jc.ui.categorypage.entity.Tag;
import com.yndsoft.jc.ui.net.util.ProgressSubscriber;
import com.yndsoft.jc.widget.SlideRecycleView;
import com.yndsoft.jc.widget.SlideRecycleViewAdapter;
import com.yndsoft.jc.widget.SlideViewHolder;
import com.yndsoft.jc.widget.flow.FlowLayout;
import com.yndsoft.jc.widget.flow.TagAdapter;
import com.yndsoft.jc.widget.flow.TagFlowLayout;
import com.yndsoft.jc.widget.pulltorefresh.PullToRefreshBase;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by hasee on 2017/12/8.
 */

public class ProductSearchActivity extends BaseActivity implements View.OnClickListener, TagFlowLayout.OnTagClickListener, SlideRecycleViewAdapter.OnItemClickListener {

    @Bind(R.id.product_search_backBtn)
    ImageView product_search_backBtn;
    @Bind(R.id.product_search_editTxt)
    EditText product_search_editTxt;
    @Bind(R.id.product_search_btn)
    TextView product_search_btn;//搜索按钮

    @Bind(R.id.product_search_emptyView)
    LinearLayout product_search_emptyView;
    @Bind(R.id.fl_myfavors)
    TagFlowLayout fl_myfavors;
    TagAdapter mAdapter;
    List<KeyValue_String> tags;

    @Bind(R.id.product_search_resultList)
    SlideRecycleView product_search_resultList;
    SearchRecyAdapter searchRecyAdapter;
    private List<Product> mData = new ArrayList<>();

    private int start = 0;
    private TextView loadAllView;
    int returnCode = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_search);


        initDefaultData();
        setViews();
        setListener();
    }

    private void initDefaultData() {
        mHttpUtil.getRecommendSearch(new ProgressSubscriber<ReturnMsg>(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                Type type = new TypeToken<List<KeyValue_String>>() {
                }.getType();
                Object fromJson = new Gson().fromJson(returnMsg.getInfo(), type);
                tags = (ArrayList<KeyValue_String>) fromJson;
                if (tags != null) {
                    fl_myfavors.setAdapter(mAdapter = new TagAdapter<KeyValue_String>(tags) {

                        @Override
                        public View getView(FlowLayout parent, int position, KeyValue_String keyValue_string) {
                            TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.favor_tag_tv,
                                    fl_myfavors, false);
                            tv.setText(keyValue_string.getValue());
                            return tv;
                        }

                    });
                }
            }
        }, "search");
    }

    private void setViews() {

        product_search_resultList.setScrollingWhileRefreshingEnabled(false); //设置刷新的时候不可滑动

        product_search_resultList.getRefreshableView().setLayoutManager(new LinearLayoutManager(this)); //添加布局管理器
        product_search_resultList.setMode(PullToRefreshBase.Mode.BOTH);
        product_search_resultList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<RecyclerView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
//                mScoreAdapter.reMoveFooterView(loadAllView);
                loadAllView.setVisibility(View.GONE);
                start = 0;
                searchContent(start);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
//                mScoreAdapter.reMoveFooterView(loadAllView);
                if (returnCode == 1) {
                    start++;
                    searchContent(start);
                } else if (returnCode == 2) {
                    loadAllView.setVisibility(View.VISIBLE);
                    product_search_resultList.onRefreshComplete();
                }

//                if (haveAnother) {
//
//                } else {
//                    mRecycleView.onRefreshComplete();
//                    mScoreAdapter.addFooterView(loadAllView);
//                }
            }
        });
        loadAllView = new TextView(this);
        loadAllView.setPadding(0, DensityUtil.dip2px(this, 10), 0, DensityUtil.dip2px(this, 10));
        loadAllView.setGravity(Gravity.CENTER);
        loadAllView.setTextSize(15);
        loadAllView.setText("已加载全部");
        searchRecyAdapter = new SearchRecyAdapter(this, mData, R.layout.item_prodct_list);
        loadAllView.setVisibility(View.GONE);
        searchRecyAdapter.addFooterView(loadAllView);
        searchRecyAdapter.setOnItemClickListener(this);
        product_search_resultList.getRefreshableView().setAdapter(searchRecyAdapter);
    }

    public float getTextWidth(String text, int textSize) {
        TextPaint paint = new TextPaint();
        float scaledDensity = this.getResources().getDisplayMetrics().scaledDensity;
        paint.setTextSize(scaledDensity * textSize);
        return paint.measureText(text);
    }

    private void setListener() {
        product_search_backBtn.setOnClickListener(this);
        product_search_btn.setOnClickListener(this);
        fl_myfavors.setOnTagClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.product_search_backBtn:
                finish();
                break;
            case R.id.product_search_btn:
                searchContent(start);
                break;
        }
    }


    private void searchContent(int start) {
        if (!TextUtils.isEmpty(product_search_editTxt.getText().toString())) {
            product_search_emptyView.setVisibility(View.GONE);
            product_search_resultList.setVisibility(View.VISIBLE);
            mHttpUtil.searchProductList(new ProgressSubscriber<ReturnMsg>(mContext) {
                @Override
                public void next(ReturnMsg returnMsg) {
                    switch (returnMsg.getCode()) {
                        case 0:

                            break;
                        case 1://有下一页
                            returnCode = 1;
                            break;
                        case 2://只有一页
                            returnCode = 2;
                            if (null != product_search_resultList) {
                                product_search_resultList.onRefreshComplete();
                            }
                            Type type1 = new TypeToken<List<Product>>() {
                            }.getType();
                            Object fromJson1 = new Gson().fromJson(returnMsg.getInfo(), type1);
                            mData = (ArrayList<Product>) fromJson1;
                            searchRecyAdapter.setDatas(mData);
                            product_search_resultList.onRefreshComplete();
                            break;
                    }
                }
            }, "searchlist", product_search_editTxt.getText().toString().trim(), start);
        } else {
            product_search_emptyView.setVisibility(View.VISIBLE);
            product_search_resultList.setVisibility(View.GONE);
            Toast.makeText(mContext, "输入内容为空", Toast.LENGTH_SHORT).show();
            mData.clear();
            searchRecyAdapter.setDatas(mData);
        }
    }

    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
        product_search_editTxt.setText(tags.get(position).getValue());
        searchContent(start);
        return true;
    }

    @Override
    public void onItemClickListener(int posotion) {

    }

    class SearchRecyAdapter extends SlideRecycleViewAdapter<Product> {


        /**
         * 构造器
         *
         * @param context
         * @param mDatas
         * @param itemLayoutId
         */
        protected SearchRecyAdapter(Context context, List<Product> mDatas, int itemLayoutId) {
            super(context, mDatas, itemLayoutId);
        }

        @Override
        public void convert(SlideViewHolder holder, final Product item) {
            ImageView product_image = holder.findViewById(R.id.product_image);
            TextView product_title = holder.findViewById(R.id.product_title);
            TextView product_price = holder.findViewById(R.id.product_price);

            Glide.with(mContext).load(item.getImg()).placeholder(R.mipmap.logo).into(product_image);
            AppUtils.setText(product_title, item.getSubname());
            AppUtils.setText(product_price, "￥" + item.getPrice());
        }

    }
}
